const mysql = require('mysql');

//  封装一个query方法
const dbconfig = {
    host: '127.0.0.1',
    user: 'root',
    password: '',
    database: 'cxblog',
    port: '3306',
    // 可以同时写多条sql语句
    multipleStatements: true
}

const pool = mysql.createPool(dbconfig)

function query(sql, params) {
    return new Promise(function(resolve, reject) {
        pool.getConnection(function(err, conn) {
            if (err) reject(err);
            conn.query(sql, params, function(err, rows) {
                if (err) reject(err);
                resolve(rows);
                conn.release();
            })
        })
    })
}
//娴前台首页
exports.index = function(req, res) {
    let sql = 'select menuName,linkUrl from menu where status=1;select imgUrl,imgName,linkUrl from banner where status=1;select classId, className from classify where status=1;select articalId,articalName,updateTime,(select userName from user where userId=artical.userId) as userName from artical where status=1 order by updateTime desc limit 0,10;';
    return query(sql);
}
exports.login = function(user) {
    let sql = 'select * from user where username=? and password=?'
    let params = [user.username, user.password]
    return query(sql, params)
}
exports.register = function(user) {
    let sql = 'insert into  user set ? ;'
    return query(sql, user)
}

exports.getOneArtical = function(id) {
    let sql = 'select *from artical where articalId=?'
    return query(sql, id)
}

//发布文章
exports.getAllClass = function() {
    let sql = 'select * from classify';
    return query(sql);
}
exports.sendArtical = function(txt) {
    let sql = 'insert into artical set ?'
    return query(sql, txt)
}